package com.yjzx.util.binlog.core.entiry.recordIndex;

import com.yjzx.util.binlog.core.constants.BaseConstant;
import com.yjzx.util.binlog.core.util.FileOperationUtil;
import com.yjzx.util.binlog.core.util.StringUtils;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @author yjzx
 * @date 2024/11/18
 * @description 文件记录获取binlog位置
 */
public class FileRecordBinLogIndex extends BinaryLogClientIndex {

    private final Path recordFile;

    public FileRecordBinLogIndex(String recordFileName) {
        recordFileName = StringUtils.isNotBlank(recordFileName) ? recordFileName : BaseConstant.BINLOG_DEFAULT_INI_NAME;
        this.recordFile = Paths.get(recordFileName);
        String[] binlogIndex = toBinlogIndex(recordFileName);
        if (binlogIndex != null && binlogIndex.length == 2) {
            this.binFileName = binlogIndex[0];
            this.position = Long.parseLong(binlogIndex[1]);
        }

    }

    @Override
    public int getOrder() {
        return 0;
    }

    @Override
    public boolean valid() {
        try {
            FileOperationUtil.createNewFile(recordFile);
        } catch (IOException ignored) {
        }
        return Files.exists(recordFile) && StringUtils.isNotBlank(binFileName) && position > 0;
    }

    @Override
    public boolean isRead() {
        return true;
    }

    @Override
    public boolean isWrite() {

        return true;
    }

    private String[] toBinlogIndex(String fileName) {
        String[] split = null;

        try {
            String line = FileOperationUtil.readLastLine(fileName);
            if (StringUtils.isNotBlank(line)) {
                split = StringUtils.split(line, BaseConstant.BINLOG_DEFAULT_INI_LINK_SEPARATOR);
                if (split.length == 2 && StringUtils.isNumber(split[1])) {
                    return split;
                }
            }
        } catch (IOException ignored) {
        }
        return null;
    }

    @Override
    public void writeBinlogIndex(String binlogIndex) {
        try {
            //防止无效数据刷新
            FileOperationUtil.writeToFile(recordFile, binlogIndex);
        } catch (IOException ignored) {
        }
    }
}
